package com.hyl.domain.trade.service.lock;

import com.hyl.domain.trade.adapter.repository.ITradeRepository;
import com.hyl.domain.trade.model.aggregate.GroupBuyOrderAggregate;
import com.hyl.domain.trade.model.entity.*;
import com.hyl.domain.trade.model.valobj.GroupBuyProgressVO;
import com.hyl.domain.trade.service.ITradeLockOrderService;
import com.hyl.domain.trade.service.lock.factory.TradeRuleFilterFactory;
import com.hyl.types.design.framework.link.moudle2.chain.BusinessLinkedList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author hyl
 * @description
 * @create 2025-07-02 10:48
 */
@Slf4j
@Service
public class TradeLockOrderService implements ITradeLockOrderService {

    @Resource
    private ITradeRepository tradeRepository;
    @Resource
    private BusinessLinkedList<TradeLockRuleCommandEntity, TradeRuleFilterFactory.DynamicContext, TradeLockRuleFilterBackEntity> tradeRuleFilter;

    @Override
    public MarketPayOrderEntity queryNoPayMarketPayOrderByOutTradeNo(String userId, String outTradeNo) {
        log.info("拼团交易——查询未支付的营销订单：{} outTradeNo:{}",userId, outTradeNo);
        return tradeRepository.queryNoPayMarketPayOrderByOutTradeNo(userId, outTradeNo);
    }

    @Override
    public GroupBuyProgressVO queryGroupBuyProgress(String teamId) {
        log.info("拼团交易-查询拼单进度：{}",teamId);
        return tradeRepository.queryGroupBuyProgress(teamId);
    }

    @Override
    public MarketPayOrderEntity lockMarketPayOrder(UserEntity userEntity, PayActivityEntity payActivityEntity, PayDiscountEntity payDiscountEntity) throws Exception {
        log.info("拼团交易-锁定营销订单：{} activityId{},goodsId{}",userEntity.getUserId(), payActivityEntity.getActivityId(), payDiscountEntity.getGoodsId());

        TradeLockRuleFilterBackEntity tradeLockRuleFilterBackEntity = tradeRuleFilter.apply(TradeLockRuleCommandEntity.builder()
                .activityId(payActivityEntity.getActivityId())
                .userId(userEntity.getUserId())
                .build(), new TradeRuleFilterFactory.DynamicContext());
        //获取使用次数
        Integer userTakeOrderCount = tradeLockRuleFilterBackEntity.getUserTakeOrderCount();

        //聚合对象
        GroupBuyOrderAggregate groupBuyOrderAggregate = GroupBuyOrderAggregate.builder()
                .userEntity(userEntity)
                .payActivityEntity(payActivityEntity)
                .payDiscountEntity(payDiscountEntity)
                .userTakeOrderCount(userTakeOrderCount)
                .build();

        /*锁定聚合订单，此时用户只是下单还没有支付后续还有流程*/
        return tradeRepository.lockMarketPayOrder(groupBuyOrderAggregate);
    }
}
